package analysis

import (
	"data-treating/pkg/calibration"
	"data-treating/pkg/types"
	"math"
)

// PoseAnalyzer 姿势分析器
type PoseAnalyzer struct {
	calibrator *calibration.Calibrator
	thresholds *AnalysisThresholds

	// 抖动过滤相关
	keypointHistory map[int][]types.Point // 每个关键点的历史位置
	historySize     int                   // 历史记录大小
	smoothingFactor float64               // 平滑因子
}

// AnalysisThresholds 分析阈值配置
type AnalysisThresholds struct {
	// 头部姿态阈值
	HeadTurnAngle   float64 // 头部转动角度阈值(度)
	HeadTiltAngle   float64 // 头部倾斜角度阈值(度)
	HeadUpwardAngle float64 // 头部上扬角度阈值(度)

	// 肩部姿态阈值
	ShoulderLevelAngle      float64 // 肩部水平角度阈值(度)
	ShoulderRetractionAngle float64 // 肩部后张角度阈值(度)

	// 身体姿态阈值
	BodyLeanAngle float64 // 身体倾斜角度阈值(度)
	BodyTurnAngle float64 // 身体转动角度阈值(度)
	BodyTiltAngle float64 // 身体倾斜角度阈值(度)

	// 腿部姿态阈值
	LegStraightAngle float64 // 腿部笔直角度阈值(度)

	// 通用阈值
	ConfidenceThreshold float64 // 置信度阈值
}

// DefaultThresholds 默认阈值
func DefaultThresholds() *AnalysisThresholds {
	return &AnalysisThresholds{
		// 头部姿态阈值 - 降低阈值，更敏感
		HeadTurnAngle:   5.0, // 头部转动5度
		HeadTiltAngle:   5.0, // 头部倾斜5度
		HeadUpwardAngle: 8.0, // 头部上扬8度

		// 肩部姿态阈值 - 降低阈值，更敏感
		ShoulderLevelAngle:      3.0, // 肩部水平3度
		ShoulderRetractionAngle: 5.0, // 肩部后张5度

		// 身体姿态阈值 - 降低阈值，更敏感
		BodyLeanAngle: 5.0, // 身体倾斜5度
		BodyTurnAngle: 8.0, // 身体转动8度
		BodyTiltAngle: 5.0, // 身体倾斜5度

		// 腿部姿态阈值 - 降低阈值，更敏感
		LegStraightAngle: 3.0, // 腿部笔直3度

		// 通用阈值
		ConfidenceThreshold: 0.5, // 50%
	}
}

// NewPoseAnalyzer 创建新的姿势分析器
func NewPoseAnalyzer() *PoseAnalyzer {
	return &PoseAnalyzer{
		calibrator: calibration.NewCalibrator(),
		thresholds: DefaultThresholds(),

		// 初始化抖动过滤
		keypointHistory: make(map[int][]types.Point),
		historySize:     5,   // 保留最近5帧的历史
		smoothingFactor: 0.7, // 平滑因子，0.7表示70%历史数据+30%当前数据
	}
}

// SetThresholds 设置分析阈值
func (pa *PoseAnalyzer) SetThresholds(thresholds *AnalysisThresholds) {
	pa.thresholds = thresholds
}

// GetCalibrator 获取校准器
func (pa *PoseAnalyzer) GetCalibrator() *calibration.Calibrator {
	return pa.calibrator
}

// GetThresholds 获取当前阈值
func (pa *PoseAnalyzer) GetThresholds() *AnalysisThresholds {
	return pa.thresholds
}

// AnalyzePose 分析姿势
func (pa *PoseAnalyzer) AnalyzePose(pose types.PoseData) (*types.PoseAnalysisResult, error) {
	calibrationData := pa.calibrator.GetCalibrationData()
	if calibrationData == nil || !calibrationData.Calibrated {
		return nil, ErrCalibrationRequired
	}

	// 应用抖动过滤
	smoothedPose := pa.smoothKeypoints(pose)

	// 应用中值滤波去除异常值
	filteredPose := pa.applyMedianFilter(smoothedPose)

	result := &types.PoseAnalysisResult{
		Timestamp: pose.Timestamp,
	}

	// 获取校准数据
	referencePose := calibrationData.AveragePose

	// 分析头部姿态
	pa.analyzeHeadPose(filteredPose, referencePose, result)

	// 分析肩部姿态
	pa.analyzeShoulderPose(filteredPose, referencePose, result)

	// 分析身体姿态
	pa.analyzeBodyPose(filteredPose, referencePose, result)

	// 分析腿部姿态
	pa.analyzeLegPose(filteredPose, referencePose, result)

	// 计算总体评分
	pa.calculateOverallScore(result)

	// 计算置信度
	pa.calculateConfidence(filteredPose, result)

	return result, nil
}

// analyzeHeadPose 分析头部姿态
func (pa *PoseAnalyzer) analyzeHeadPose(pose, referencePose types.PoseData, result *types.PoseAnalysisResult) {
	nose := pose.Keypoints[types.Nose]
	leftEye := pose.Keypoints[types.LeftEye]
	rightEye := pose.Keypoints[types.RightEye]
	leftEar := pose.Keypoints[types.LeftEar]
	rightEar := pose.Keypoints[types.RightEar]

	refNose := referencePose.Keypoints[types.Nose]
	refLeftEye := referencePose.Keypoints[types.LeftEye]
	refRightEye := referencePose.Keypoints[types.RightEye]
	refLeftEar := referencePose.Keypoints[types.LeftEar]
	refRightEar := referencePose.Keypoints[types.RightEar]

	if !nose.IsValid() || !leftEye.IsValid() || !rightEye.IsValid() ||
		!refNose.IsValid() || !refLeftEye.IsValid() || !refRightEye.IsValid() {
		return
	}

	// 获取校准数据
	calibrationData := pa.calibrator.GetCalibrationData()

	// 分析头部左右转动
	if leftEar.IsValid() && rightEar.IsValid() && refLeftEar.IsValid() && refRightEar.IsValid() {
		// 计算当前姿势的眼睛和耳朵中点
		eyeMidX := (leftEye.X + rightEye.X) / 2
		earMidX := (leftEar.X + rightEar.X) / 2

		// 计算参考姿势的眼睛和耳朵中点
		refEyeMidX := (refLeftEye.X + refRightEye.X) / 2
		refEarMidX := (refLeftEar.X + refRightEar.X) / 2

		// 计算头部转动角度（相对于参考姿势的偏移）
		headTurnOffset := (earMidX - eyeMidX) - (refEarMidX - refEyeMidX)
		headTurnAngle := math.Atan2(headTurnOffset, leftEar.Y-leftEye.Y) * 180 / math.Pi

		// 使用标准差动态调整阈值
		headTurnThreshold := pa.calculateDynamicThreshold(calibrationData, []int{
			types.LeftEye, types.RightEye, types.LeftEar, types.RightEar,
		})

		if headTurnAngle > headTurnThreshold {
			result.HeadTurnRight = headTurnAngle - headTurnThreshold
		} else if headTurnAngle < -headTurnThreshold {
			result.HeadTurnLeft = -(headTurnAngle + headTurnThreshold)
		}
	}

	// 分析头部左右倾斜 - 使用距离检测
	headTiltDistanceDeviation := pa.calculateDistanceDeviation(pose, referencePose, []int{
		types.LeftEye, types.RightEye,
	})

	// 计算参考距离（眼睛间距）
	refEyeDistance := refLeftEye.Distance(refRightEye)
	headTiltDeviation := pa.calculateAngleFromDistance(headTiltDistanceDeviation, refEyeDistance)

	headTiltThreshold := pa.calculateDynamicThreshold(calibrationData, []int{
		types.LeftEye, types.RightEye,
	})

	if headTiltDeviation > headTiltThreshold {
		result.HeadTiltRight = headTiltDeviation - headTiltThreshold
	} else if headTiltDeviation < -headTiltThreshold {
		result.HeadTiltLeft = -(headTiltDeviation + headTiltThreshold)
	}

	// 分析头部前后倾斜 - 使用距离检测
	headTiltForwardDistanceDeviation := pa.calculateDistanceDeviation(pose, referencePose, []int{
		types.Nose, types.LeftEye, types.RightEye,
	})

	// 计算参考距离（鼻子到眼睛中点的距离）
	refEyeMidX := (refLeftEye.X + refRightEye.X) / 2
	refEyeMidY := (refLeftEye.Y + refRightEye.Y) / 2
	refNoseToEyeDistance := math.Sqrt((refNose.X-refEyeMidX)*(refNose.X-refEyeMidX) + (refNose.Y-refEyeMidY)*(refNose.Y-refEyeMidY))
	headTiltForwardDeviation := pa.calculateAngleFromDistance(headTiltForwardDistanceDeviation, refNoseToEyeDistance)

	headTiltForwardThreshold := pa.calculateDynamicThreshold(calibrationData, []int{
		types.Nose, types.LeftEye, types.RightEye,
	})

	if headTiltForwardDeviation > headTiltForwardThreshold {
		result.HeadTiltForward = headTiltForwardDeviation - headTiltForwardThreshold
	} else if headTiltForwardDeviation < -headTiltForwardThreshold {
		result.HeadTiltBackward = -(headTiltForwardDeviation + headTiltForwardThreshold)
	}

	// 分析头部上扬 - 使用距离检测
	headUpwardDistanceDeviation := pa.calculateDistanceDeviation(pose, referencePose, []int{
		types.Nose, types.LeftEye, types.RightEye,
	})
	headUpwardDeviation := pa.calculateAngleFromDistance(headUpwardDistanceDeviation, refNoseToEyeDistance)

	headUpwardThreshold := pa.calculateDynamicThreshold(calibrationData, []int{
		types.Nose, types.LeftEye, types.RightEye,
	})

	if headUpwardDeviation > headUpwardThreshold {
		result.HeadUpward = headUpwardDeviation - headUpwardThreshold
	}
}

// analyzeLegPoseWithCalibration 基于校准数据分析腿部姿态

// analyzeShoulderPose 分析肩部姿态
func (pa *PoseAnalyzer) analyzeShoulderPose(pose, referencePose types.PoseData, result *types.PoseAnalysisResult) {
	leftShoulder := pose.Keypoints[types.LeftShoulder]
	rightShoulder := pose.Keypoints[types.RightShoulder]

	refLeftShoulder := referencePose.Keypoints[types.LeftShoulder]
	refRightShoulder := referencePose.Keypoints[types.RightShoulder]

	if !leftShoulder.IsValid() || !rightShoulder.IsValid() ||
		!refLeftShoulder.IsValid() || !refRightShoulder.IsValid() {
		return
	}

	// 获取校准数据
	calibrationData := pa.calibrator.GetCalibrationData()

	// 分析两肩水平度 - 使用距离检测
	shoulderLevelDistanceDeviation := pa.calculateDistanceDeviation(pose, referencePose, []int{
		types.LeftShoulder, types.RightShoulder,
	})

	// 计算参考距离（肩膀间距）
	refShoulderDistance := refLeftShoulder.Distance(refRightShoulder)
	shoulderLevelDeviation := pa.calculateAngleFromDistance(shoulderLevelDistanceDeviation, refShoulderDistance)

	shoulderLevelThreshold := pa.calculateDynamicThreshold(calibrationData, []int{
		types.LeftShoulder, types.RightShoulder,
	})

	if shoulderLevelDeviation > shoulderLevelThreshold {
		result.ShoulderLevel = shoulderLevelDeviation - shoulderLevelThreshold
	}

	// 分析两肩后张 - 使用距离检测
	shoulderRetractionDistanceDeviation := pa.calculateDistanceDeviation(pose, referencePose, []int{
		types.LeftShoulder, types.RightShoulder,
	})
	shoulderRetractionDeviation := pa.calculateAngleFromDistance(shoulderRetractionDistanceDeviation, refShoulderDistance)

	shoulderRetractionThreshold := pa.calculateDynamicThreshold(calibrationData, []int{
		types.LeftShoulder, types.RightShoulder,
	})

	if shoulderRetractionDeviation > shoulderRetractionThreshold {
		result.ShoulderRetraction = shoulderRetractionDeviation - shoulderRetractionThreshold
	}
}

// analyzeBodyPose 分析身体姿态
func (pa *PoseAnalyzer) analyzeBodyPose(pose, referencePose types.PoseData, result *types.PoseAnalysisResult) {
	leftShoulder := pose.Keypoints[types.LeftShoulder]
	rightShoulder := pose.Keypoints[types.RightShoulder]
	leftHip := pose.Keypoints[types.LeftHip]
	rightHip := pose.Keypoints[types.RightHip]

	refLeftShoulder := referencePose.Keypoints[types.LeftShoulder]
	refRightShoulder := referencePose.Keypoints[types.RightShoulder]
	refLeftHip := referencePose.Keypoints[types.LeftHip]
	refRightHip := referencePose.Keypoints[types.RightHip]

	if !leftShoulder.IsValid() || !rightShoulder.IsValid() ||
		!leftHip.IsValid() || !rightHip.IsValid() ||
		!refLeftShoulder.IsValid() || !refRightShoulder.IsValid() ||
		!refLeftHip.IsValid() || !refRightHip.IsValid() {
		return
	}

	// 获取校准数据
	calibrationData := pa.calibrator.GetCalibrationData()

	// 计算参考姿势的肩膀和髋部中点
	refShoulderMidX := (refLeftShoulder.X + refRightShoulder.X) / 2
	refShoulderMidY := (refLeftShoulder.Y + refRightShoulder.Y) / 2
	refHipMidX := (refLeftHip.X + refRightHip.X) / 2
	refHipMidY := (refLeftHip.Y + refRightHip.Y) / 2

	// 分析身体左右转动 - 使用距离检测
	bodyTurnDistanceDeviation := pa.calculateDistanceDeviation(pose, referencePose, []int{
		types.LeftShoulder, types.RightShoulder, types.LeftHip, types.RightHip,
	})

	// 计算参考距离（肩膀中点到髋部中点的距离）
	refShoulderToHipDistance := math.Sqrt((refShoulderMidX-refHipMidX)*(refShoulderMidX-refHipMidX) + (refShoulderMidY-refHipMidY)*(refShoulderMidY-refHipMidY))
	bodyTurnDeviation := pa.calculateAngleFromDistance(bodyTurnDistanceDeviation, refShoulderToHipDistance)

	bodyTurnThreshold := pa.calculateDynamicThreshold(calibrationData, []int{
		types.LeftShoulder, types.RightShoulder, types.LeftHip, types.RightHip,
	})

	if bodyTurnDeviation > bodyTurnThreshold {
		result.BodyTurnRight = bodyTurnDeviation - bodyTurnThreshold
	} else if bodyTurnDeviation < -bodyTurnThreshold {
		result.BodyTurnLeft = -(bodyTurnDeviation + bodyTurnThreshold)
	}

	// 分析身体左右倾斜 - 使用距离检测
	bodyTiltDistanceDeviation := pa.calculateDistanceDeviation(pose, referencePose, []int{
		types.LeftShoulder, types.RightShoulder,
	})

	// 计算参考距离（肩膀间距）
	refShoulderDistance := refLeftShoulder.Distance(refRightShoulder)
	bodyTiltDeviation := pa.calculateAngleFromDistance(bodyTiltDistanceDeviation, refShoulderDistance)

	bodyTiltThreshold := pa.calculateDynamicThreshold(calibrationData, []int{
		types.LeftShoulder, types.RightShoulder,
	})

	if bodyTiltDeviation > bodyTiltThreshold {
		result.BodyTiltRight = bodyTiltDeviation - bodyTiltThreshold
	} else if bodyTiltDeviation < -bodyTiltThreshold {
		result.BodyTiltLeft = -(bodyTiltDeviation + bodyTiltThreshold)
	}

	// 分析身体前后倾斜 - 使用距离检测
	bodyLeanDistanceDeviation := pa.calculateDistanceDeviation(pose, referencePose, []int{
		types.LeftShoulder, types.RightShoulder, types.LeftHip, types.RightHip,
	})
	bodyLeanDeviation := pa.calculateAngleFromDistance(bodyLeanDistanceDeviation, refShoulderToHipDistance)

	bodyLeanThreshold := pa.calculateDynamicThreshold(calibrationData, []int{
		types.LeftShoulder, types.RightShoulder, types.LeftHip, types.RightHip,
	})

	if bodyLeanDeviation > bodyLeanThreshold {
		result.BodyLeanForward = bodyLeanDeviation - bodyLeanThreshold
	} else if bodyLeanDeviation < -bodyLeanThreshold {
		result.BodyLeanBackward = -(bodyLeanDeviation + bodyLeanThreshold)
	}
}

// analyzeLegPose 分析腿部姿态
func (pa *PoseAnalyzer) analyzeLegPose(pose, referencePose types.PoseData, result *types.PoseAnalysisResult) {
	leftHip := pose.Keypoints[types.LeftHip]
	rightHip := pose.Keypoints[types.RightHip]
	leftKnee := pose.Keypoints[types.LeftKnee]
	rightKnee := pose.Keypoints[types.RightKnee]
	leftAnkle := pose.Keypoints[types.LeftAnkle]
	rightAnkle := pose.Keypoints[types.RightAnkle]

	refLeftHip := referencePose.Keypoints[types.LeftHip]
	refRightHip := referencePose.Keypoints[types.RightHip]
	refLeftKnee := referencePose.Keypoints[types.LeftKnee]
	refRightKnee := referencePose.Keypoints[types.RightKnee]
	refLeftAnkle := referencePose.Keypoints[types.LeftAnkle]
	refRightAnkle := referencePose.Keypoints[types.RightAnkle]

	if !leftHip.IsValid() || !rightHip.IsValid() ||
		!leftKnee.IsValid() || !rightKnee.IsValid() ||
		!leftAnkle.IsValid() || !rightAnkle.IsValid() ||
		!refLeftHip.IsValid() || !refRightHip.IsValid() ||
		!refLeftKnee.IsValid() || !refRightKnee.IsValid() ||
		!refLeftAnkle.IsValid() || !refRightAnkle.IsValid() {
		return
	}

	// 获取校准数据
	calibrationData := pa.calibrator.GetCalibrationData()

	// 分析左腿笔直度
	leftLegAngle := types.Angle(leftHip, leftKnee, leftAnkle)
	refLeftLegAngle := types.Angle(refLeftHip, refLeftKnee, refLeftAnkle)
	leftLegDeviation := math.Abs(leftLegAngle - refLeftLegAngle)

	// 分析右腿笔直度
	rightLegAngle := types.Angle(rightHip, rightKnee, rightAnkle)
	refRightLegAngle := types.Angle(refRightHip, refRightKnee, refRightAnkle)
	rightLegDeviation := math.Abs(rightLegAngle - refRightLegAngle)

	legStraightThreshold := pa.calculateDynamicThreshold(calibrationData, []int{
		types.LeftHip, types.RightHip, types.LeftKnee, types.RightKnee, types.LeftAnkle, types.RightAnkle,
	})

	leftLegStraight := leftLegDeviation <= legStraightThreshold
	rightLegStraight := rightLegDeviation <= legStraightThreshold

	result.LegsStraight = leftLegStraight && rightLegStraight
}

// calculateOverallScore 计算总体评分
func (pa *PoseAnalyzer) calculateOverallScore(result *types.PoseAnalysisResult) {
	score := 100.0
	deductions := 0.0

	// 头部姿态扣分
	if result.HeadTurnLeft > 0 {
		deductions += result.HeadTurnLeft * 2.0
	}
	if result.HeadTurnRight > 0 {
		deductions += result.HeadTurnRight * 2.0
	}
	if result.HeadTiltLeft > 0 {
		deductions += result.HeadTiltLeft * 1.5
	}
	if result.HeadTiltRight > 0 {
		deductions += result.HeadTiltRight * 1.5
	}
	if result.HeadTiltForward > 0 {
		deductions += result.HeadTiltForward * 2.0
	}
	if result.HeadTiltBackward > 0 {
		deductions += result.HeadTiltBackward * 2.0
	}
	if result.HeadUpward > 0 {
		deductions += result.HeadUpward * 1.0
	}

	// 肩部姿态扣分
	if result.ShoulderLevel > 0 {
		deductions += result.ShoulderLevel * 2.0
	}
	if result.ShoulderRetraction > 0 {
		deductions += result.ShoulderRetraction * 1.5
	}

	// 身体姿态扣分
	if result.BodyTurnLeft > 0 {
		deductions += result.BodyTurnLeft * 2.5
	}
	if result.BodyTurnRight > 0 {
		deductions += result.BodyTurnRight * 2.5
	}
	if result.BodyTiltLeft > 0 {
		deductions += result.BodyTiltLeft * 2.0
	}
	if result.BodyTiltRight > 0 {
		deductions += result.BodyTiltRight * 2.0
	}
	if result.BodyLeanForward > 0 {
		deductions += result.BodyLeanForward * 3.0
	}
	if result.BodyLeanBackward > 0 {
		deductions += result.BodyLeanBackward * 3.0
	}

	// 腿部姿态扣分
	if !result.LegsStraight {
		deductions += 10.0
	}

	// 计算最终评分
	result.OverallScore = math.Max(0, score-deductions)
	result.IsStandingStraight = result.OverallScore >= 80.0
}

// calculateConfidence 计算检测置信度
func (pa *PoseAnalyzer) calculateConfidence(pose types.PoseData, result *types.PoseAnalysisResult) {
	validKeypoints := 0
	totalConfidence := 0.0
	anomalyCount := 0

	calibrationData := pa.calibrator.GetCalibrationData()
	referencePose := calibrationData.AveragePose

	for i, keypoint := range pose.Keypoints {
		if keypoint.IsValid() {
			validKeypoints++
			totalConfidence += keypoint.Confidence

			// 检查是否为异常点（偏离平均值超过2个标准差）
			if i < len(calibrationData.StandardDeviations) && i < len(referencePose.Keypoints) {
				refKeypoint := referencePose.Keypoints[i]
				stdDev := calibrationData.StandardDeviations[i]

				if refKeypoint.IsValid() && stdDev.Confidence > 0 {
					// 计算当前点与参考点的距离
					dx := keypoint.X - refKeypoint.X
					dy := keypoint.Y - refKeypoint.Y
					distance := math.Sqrt(dx*dx + dy*dy)

					// 计算标准差距离
					stdDevDistance := math.Sqrt(stdDev.X*stdDev.X + stdDev.Y*stdDev.Y)

					// 如果距离超过2个标准差，标记为异常
					if stdDevDistance > 0 && distance > stdDevDistance*2 {
						anomalyCount++
					}
				}
			}
		}
	}

	if validKeypoints > 0 {
		baseConfidence := totalConfidence / float64(validKeypoints)

		// 基于异常点数量调整置信度
		anomalyPenalty := float64(anomalyCount) / float64(validKeypoints) * 0.3 // 每个异常点扣30%

		result.Confidence = math.Max(0, baseConfidence-anomalyPenalty)
	} else {
		result.Confidence = 0
	}
}

// calculateDynamicThreshold 基于校准数据的标准差计算动态阈值
func (pa *PoseAnalyzer) calculateDynamicThreshold(calibrationData *types.CalibrationData, keypointIndices []int) float64 {
	// 计算相关关键点的平均标准差
	var totalStdDev float64
	validCount := 0

	for _, idx := range keypointIndices {
		if idx < len(calibrationData.StandardDeviations) {
			stdDev := calibrationData.StandardDeviations[idx]
			// 使用X和Y方向标准差的平均值
			avgStdDev := (stdDev.X + stdDev.Y) / 2
			totalStdDev += avgStdDev
			validCount++
		}
	}

	if validCount == 0 {
		return pa.thresholds.BodyLeanAngle // 使用默认阈值
	}

	avgStdDev := totalStdDev / float64(validCount)

	// 基于标准差调整阈值：标准差越大，阈值越宽松
	// 使用1.0倍标准差作为基础（更敏感），但不超过默认阈值的1.5倍
	dynamicThreshold := math.Min(avgStdDev*1.0, pa.thresholds.BodyLeanAngle*1.5)

	// 确保阈值不小于默认值的0.3倍（更敏感）
	return math.Max(dynamicThreshold, pa.thresholds.BodyLeanAngle*0.3)
}

// calculateVerticalAngle 计算垂直角度
func (pa *PoseAnalyzer) calculateVerticalAngle(x1, y1, x2, y2 float64) float64 {
	dx := x2 - x1
	dy := y2 - y1

	if dx == 0 {
		return 0
	}

	angle := math.Atan2(dx, dy) * 180 / math.Pi
	return angle
}

// calculateHorizontalAngle 计算水平角度
func (pa *PoseAnalyzer) calculateHorizontalAngle(x1, y1, x2, y2 float64) float64 {
	dx := x2 - x1
	dy := y2 - y1

	if dy == 0 {
		return 0
	}

	angle := math.Atan2(dx, dy) * 180 / math.Pi
	return angle
}

// smoothKeypoints 平滑关键点数据，减少抖动
func (pa *PoseAnalyzer) smoothKeypoints(pose types.PoseData) types.PoseData {
	smoothedPose := pose

	for i, keypoint := range pose.Keypoints {
		if keypoint.IsValid() {
			// 获取该关键点的历史记录
			history, exists := pa.keypointHistory[i]
			if !exists {
				history = make([]types.Point, 0)
			}

			// 添加当前关键点到历史记录
			history = append(history, keypoint)

			// 保持历史记录大小
			if len(history) > pa.historySize {
				history = history[len(history)-pa.historySize:]
			}

			// 更新历史记录
			pa.keypointHistory[i] = history

			// 计算平滑后的位置
			smoothedPoint := pa.calculateSmoothedPosition(history)
			smoothedPose.Keypoints[i] = smoothedPoint
		}
	}

	return smoothedPose
}

// calculateSmoothedPosition 计算平滑后的位置
func (pa *PoseAnalyzer) calculateSmoothedPosition(history []types.Point) types.Point {
	if len(history) == 0 {
		return types.Point{}
	}

	if len(history) == 1 {
		return history[0]
	}

	// 使用加权移动平均进行平滑
	var weightedX, weightedY, weightedConf float64
	var totalWeight float64

	for i, point := range history {
		// 越新的数据权重越大
		weight := math.Pow(pa.smoothingFactor, float64(len(history)-1-i))

		weightedX += point.X * weight
		weightedY += point.Y * weight
		weightedConf += point.Confidence * weight
		totalWeight += weight
	}

	if totalWeight > 0 {
		return types.Point{
			X:          weightedX / totalWeight,
			Y:          weightedY / totalWeight,
			Confidence: weightedConf / totalWeight,
		}
	}

	return history[len(history)-1] // 返回最新的点
}

// applyMedianFilter 应用中值滤波
func (pa *PoseAnalyzer) applyMedianFilter(pose types.PoseData) types.PoseData {
	filteredPose := pose

	for i, keypoint := range pose.Keypoints {
		if keypoint.IsValid() {
			history, exists := pa.keypointHistory[i]
			if exists && len(history) >= 3 {
				// 对X坐标应用中值滤波
				xValues := make([]float64, len(history))
				for j, point := range history {
					xValues[j] = point.X
				}
				medianX := pa.calculateMedian(xValues)

				// 对Y坐标应用中值滤波
				yValues := make([]float64, len(history))
				for j, point := range history {
					yValues[j] = point.Y
				}
				medianY := pa.calculateMedian(yValues)

				// 如果当前值与中值差异过大，使用中值
				if math.Abs(keypoint.X-medianX) > 10 || math.Abs(keypoint.Y-medianY) > 10 {
					filteredPose.Keypoints[i] = types.Point{
						X:          medianX,
						Y:          medianY,
						Confidence: keypoint.Confidence,
					}
				}
			}
		}
	}

	return filteredPose
}

// calculateMedian 计算中值
func (pa *PoseAnalyzer) calculateMedian(values []float64) float64 {
	if len(values) == 0 {
		return 0
	}

	// 复制数组并排序
	sorted := make([]float64, len(values))
	copy(sorted, values)

	// 简单的冒泡排序
	for i := 0; i < len(sorted)-1; i++ {
		for j := 0; j < len(sorted)-1-i; j++ {
			if sorted[j] > sorted[j+1] {
				sorted[j], sorted[j+1] = sorted[j+1], sorted[j]
			}
		}
	}

	// 返回中值
	if len(sorted)%2 == 0 {
		return (sorted[len(sorted)/2-1] + sorted[len(sorted)/2]) / 2
	}
	return sorted[len(sorted)/2]
}

// applyKalmanFilter 应用卡尔曼滤波（简化版本）
func (pa *PoseAnalyzer) applyKalmanFilter(pose types.PoseData) types.PoseData {
	filteredPose := pose

	for i, keypoint := range pose.Keypoints {
		if keypoint.IsValid() {
			history, exists := pa.keypointHistory[i]
			if exists && len(history) >= 2 {
				// 简化的卡尔曼滤波
				prevPoint := history[len(history)-1]

				// 预测步骤：假设位置不变
				predictedX := prevPoint.X
				predictedY := prevPoint.Y

				// 更新步骤：结合预测值和测量值
				kalmanGain := 0.3 // 卡尔曼增益
				filteredX := predictedX + kalmanGain*(keypoint.X-predictedX)
				filteredY := predictedY + kalmanGain*(keypoint.Y-predictedY)

				filteredPose.Keypoints[i] = types.Point{
					X:          filteredX,
					Y:          filteredY,
					Confidence: keypoint.Confidence,
				}
			}
		}
	}

	return filteredPose
}

// SetSmoothingFactor 设置平滑因子
func (pa *PoseAnalyzer) SetSmoothingFactor(factor float64) {
	if factor >= 0 && factor <= 1 {
		pa.smoothingFactor = factor
	}
}

// SetHistorySize 设置历史记录大小
func (pa *PoseAnalyzer) SetHistorySize(size int) {
	if size > 0 && size <= 20 {
		pa.historySize = size
	}
}

// ClearHistory 清除历史记录
func (pa *PoseAnalyzer) ClearHistory() {
	pa.keypointHistory = make(map[int][]types.Point)
}

// GetSmoothingFactor 获取当前平滑因子
func (pa *PoseAnalyzer) GetSmoothingFactor() float64 {
	return pa.smoothingFactor
}

// GetHistorySize 获取当前历史记录大小
func (pa *PoseAnalyzer) GetHistorySize() int {
	return pa.historySize
}

// GetSmoothedPose 获取去抖动后的姿势数据
func (pa *PoseAnalyzer) GetSmoothedPose(pose types.PoseData) types.PoseData {
	// 应用抖动过滤
	smoothedPose := pa.smoothKeypoints(pose)

	// 应用中值滤波去除异常值
	filteredPose := pa.applyMedianFilter(smoothedPose)

	return filteredPose
}

// normalizeAngle 将角度标准化到 -180 到 180 度范围
func (pa *PoseAnalyzer) normalizeAngle(angle float64) float64 {
	// 将角度限制在 -180 到 180 度范围内
	for angle > 180 {
		angle -= 360
	}
	for angle < -180 {
		angle += 360
	}
	return angle
}

// calculateAngleDifference 计算两个角度之间的差值（考虑角度环绕）
func (pa *PoseAnalyzer) calculateAngleDifference(angle1, angle2 float64) float64 {
	diff := angle1 - angle2
	return pa.normalizeAngle(diff)
}

// calculateDistanceDeviation 计算关键点距离偏差
func (pa *PoseAnalyzer) calculateDistanceDeviation(pose, referencePose types.PoseData, keypointIndices []int) float64 {
	var totalDeviation float64
	validCount := 0

	for _, idx := range keypointIndices {
		if idx < len(pose.Keypoints) && idx < len(referencePose.Keypoints) {
			current := pose.Keypoints[idx]
			reference := referencePose.Keypoints[idx]

			if current.IsValid() && reference.IsValid() {
				// 计算欧几里得距离
				dx := current.X - reference.X
				dy := current.Y - reference.Y
				distance := math.Sqrt(dx*dx + dy*dy)
				totalDeviation += distance
				validCount++
			}
		}
	}

	if validCount == 0 {
		return 0
	}

	return totalDeviation / float64(validCount)
}

// calculateAngleFromDistance 基于距离偏差计算角度偏差
func (pa *PoseAnalyzer) calculateAngleFromDistance(distanceDeviation float64, referenceDistance float64) float64 {
	if referenceDistance == 0 {
		return 0
	}
	// 使用反正切计算角度偏差
	return math.Atan2(distanceDeviation, referenceDistance) * 180 / math.Pi
}
